package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.dto.DocumentReplenishAmendQueryDto;
import com.icinfo.cloud.provider.punish.dto.DocumentReplenishAmendSaveDto;
import com.icinfo.cloud.provider.punish.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.vo.DocumentReplenishAmendDetailVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.tools.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author shishengyao
 * @description
 * @date 2023/2/21
 */
@Service
public class DocumentReplenishAmendServiceImpl extends MyBatisServiceSupport implements IDocumentReplenishAmendService {
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private IAppCaseBeforeDocumentRecordService appCaseBeforeDocumentRecordService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;

    @Override
    public int replenishAmendDocument(DocumentReplenishAmendSaveDto saveDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new com.icinfo.cloud.provider.common.exception.BusinessException("登录失效");
        }
        int count = 0;
        //简易程序
        if (Constant.STRING_1.equals(saveDto.getSourceType())) {
            count = replenishAmendSimpleCaseDocument(saveDto, userInfo);

        }
        return count;
    }


    @Override
    public DocumentReplenishAmendDetailVo getReplenishAmendDetail(DocumentReplenishAmendQueryDto queryDto) {
        DocumentReplenishAmendDetailVo detailVo = null;
        //简易程序
        if (Constant.STRING_1.equals(queryDto.getSourceType())) {
            detailVo = getReplenishAmendSimpleCaseDocument(queryDto);

        }
        // 扩展办案直通车，暂时没有
        return detailVo;
    }

    /**
     * 描述：获取简易程序补正/更正内容
     *
     * @author shishengyao
     * @date 2023/02/24
     */
    private DocumentReplenishAmendDetailVo getReplenishAmendSimpleCaseDocument(DocumentReplenishAmendQueryDto queryDto) {
        DocumentReplenishAmendDetailVo detailVo = new DocumentReplenishAmendDetailVo();
        detailVo.setTemplateType("narrow");
        //如果有补正
        if (StringUtils.isNotEmpty(queryDto.getReplenishAmendDocumentId())) {
            CaseDocumentRecordVo caseDocumentRecordInfo = caseDocumentRecordService.getCaseDocumentRecordInfo(queryDto.getReplenishAmendDocumentId());
            String documentContent = caseDocumentRecordInfo.getDocumentContent();
            detailVo = JSON.parseObject(documentContent, DocumentReplenishAmendDetailVo.class);
            detailVo.setAmendDocumentId(queryDto.getReplenishAmendDocumentId());
            detailVo.setCaseId(queryDto.getCaseId());
            detailVo.setAmendDocumentId(caseDocumentRecordInfo.getId());
        } else {
            String caseId = queryDto.getCaseId();
            String documentName = "简易程序处罚决定书";
            CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
            if (ObjectUtil.isEmpty(caseMainInfo)) {
                throw new BusinessException("当前案件不存在");
            }
            //文书目录信息
            ConfigBusiParamDocumentInfo configBusiParam = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK2BZGZTZS.getCode(),"JYCX");
            if (ObjectUtil.isEmpty(configBusiParam)) {
                throw new BusinessException("当前案件暂未配置补正/更正文书");
            }
            detailVo.setDocumentTemplateCode(configBusiParam.getTemplatePersonCode());
            detailVo.setDocumentCatalogCode(configBusiParam.getDocumentCatalogCode());
            detailVo.setCaseId(queryDto.getCaseId());
            //单位参数信息
            SysDepartParam sysdepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
            detailVo.setOrgStandardName(sysdepartParam.getOrgStandardName());
            detailVo.setOrgStandardNameSealLocation(sysdepartParam.getOrgStandardName());
            //文书信息
            CaseDocumentRecordVo documentInfo = caseDocumentRecordService.getCaseDocumentRecordInfo(queryDto.getDocumentId());
            detailVo.setDocumentNameAndNumber(documentName + documentInfo.getDocumentNumber());
            detailVo.setSendDate(ObjectUtil.isNotEmpty(documentInfo.getSentTime())?documentInfo.getSentTime().toLocalDate():null);
            //当事人信息
            List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(caseId);
            String partyName = casePartiesInfo.get(0).getPartyName();
            detailVo.setPartyName(partyName);
            detailVo.setDocumentTitle(documentName + "补正/更正通知书");
            detailVo.setBeforeAmendDesc("补正/更正前：");
            detailVo.setAfterAmendDesc("补正/更正后：");
            detailVo.setAmendKindDesc("补正/更正");
            detailVo.setDocumentSealDate(LocalDate.now());
        }

        return detailVo;
    }

    /**
     * 描述：补正/更正简易程序
     *
     * @author shishengyao
     * @date 2023/02/24
     */
    private int replenishAmendSimpleCaseDocument(DocumentReplenishAmendSaveDto saveDto, UserDTO userInfo) {
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        if (ObjectUtil.isEmpty(caseMainInfo)) {
            throw new BusinessException("当前案件不存在");
        }
        caseDocumentRecordService.getCaseDocumentRecordInfo(saveDto.getDocumentId());
        ConfigBusiParamDocumentInfo configBusiParam = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK2BZGZTZS.getCode(),"JYCX");
        LocalDateTime now = LocalDateTime.now();
        String caseId = saveDto.getCaseId();
        //添加文号
        String documentCatalogCode = configBusiParam.getDocumentCatalogCode();
        String documentNumber = caseDocumentRecordService.getCommonDocumentNumber(caseId,configBusiParam.getDocumentCatalogCode());
        //添加补正更正文号
        saveDto.setDocumentNumber(documentNumber);
        //生成pdf
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        // app端文书默认取窄幅文书
        pdfRequest.setTemplateType("narrow");
        pdfRequest.setTemplateCode(configBusiParam.getTemplatePersonCode());
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(saveDto));
        pdfRequest.setParamMap(jsonObject);
        Map<String, String> unSealPdfUrl = appCaseBeforeDocumentRecordService.getConvertedPdfUrl(pdfRequest);
        // 生成带签章的文书
        String pdfSealUrl = "";
        if (Constant.STRING_1.equals(configBusiParam.getIsDeptSign())) {
            FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
            SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userInfo.getOrgCode(), userInfo.getDeptCode());
            queryDto.setUniscid(sysDepartParam.getUnicode());
            queryDto.setFileBase64(unSealPdfUrl.get("fileBase64"));
            queryDto.setDeptCode(userInfo.getDeptCode());
            pdfSealUrl = appCaseBeforeDocumentRecordService.dealFileSeal(queryDto);
        }
        //生成并保存文书
        CaseDocumentRecord documentRecord = new CaseDocumentRecord();
        documentRecord.setRelationDocumentId(saveDto.getDocumentId());
        documentRecord.setDocumentUrl(unSealPdfUrl.get("fileUrl"));
        documentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
        int count;
        if (ObjectUtil.isEmpty(saveDto.getReplenishAmendId())) {
            documentRecord.setDocumentCatalogCode(documentCatalogCode);
            documentRecord.setDocumentCreateTime(now);
            documentRecord.setRelationDocumentId(saveDto.getDocumentId());
            documentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
            documentRecord.setId(BaseUtil.createUid());
            documentRecord.setCaseId(saveDto.getCaseId());
            documentRecord.setDocumentTemplateCode(configBusiParam.getTemplatePersonCode());
            documentRecord.setCreateUserId(userInfo.getUserId() + "");
            documentRecord.setCreateUserName(userInfo.getRealName());
            documentRecord.setDocumentContent(JSONObject.toJSON(saveDto).toString());
            documentRecord.setDocumentNumber(documentNumber);
            documentRecord.setCaseLinkCode(caseMainInfo.getCaseCurrentLinkCode());
            documentRecord.setCaseLinkName(caseMainInfo.getLineName());
            documentRecord.setCaseStageCode(caseMainInfo.getCaseCurrentStageCode());
            documentRecord.setCaseStageName(caseMainInfo.getCaseCurrentStageName());
            count = caseDocumentRecordMapper.insertSelective(documentRecord);
        } else {
            documentRecord.setDocumentCatalogCode(configBusiParam.getDocumentCatalogCode());
            documentRecord.setId(saveDto.getReplenishAmendId());
            documentRecord.setDocumentContent(JSONObject.toJSON(saveDto).toString());
            count = caseDocumentRecordMapper.updateByPrimaryKeySelective(documentRecord);
        }

        return count;
    }
}
